package com.xgxx.chendawei.config;


import com.xgxx.chendawei.system.utils.api.ApiResponseUtil;
import com.xgxx.chendawei.system.utils.api.BusinessException;
import com.xgxx.chendawei.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 异常处理
 */
@ControllerAdvice
@Slf4j
public class WebExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Object invoke(HttpServletRequest request, HttpServletResponse response, Exception e) {
        try (PrintWriter out = response.getWriter()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            log.debug("", e);
            if (e instanceof BusinessException) {
                out.write(JsonUtil.beanToJson(ApiResponseUtil.getApiResponse(((BusinessException) e).getCode(), e.getMessage())));
            } else if (e instanceof MethodArgumentNotValidException) {
                BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
                String errorMesssage = "校验失败:";
                for (FieldError fieldError : bindingResult.getFieldErrors()) {
                    errorMesssage += fieldError.getDefaultMessage() + ", ";
                }
                out.write(JsonUtil.beanToJson(ApiResponseUtil.getCommErrorApiResponse(errorMesssage)));
            } else if (e instanceof SQLIntegrityConstraintViolationException) {
                out.write(JsonUtil.beanToJson(ApiResponseUtil.getCommErrorApiResponse("数据库中唯一键冲突")));
            } else {
                log.error("", e);
                out.write(JsonUtil.beanToJson(ApiResponseUtil.getCommErrorApiResponse("系统发生未知异常")));
            }
            out.flush();
        } catch (Exception ex) {
            log.error("", ex);
        }
        return null;
    }

}
